from django.contrib.auth.models import BaseUserManager
from django.contrib.auth.models import Group

# 自定义用户模型管理器
from django.db import transaction
from django.db.models import Q, F


class UserManager(BaseUserManager):

    def set_default_group(self, user):
        group = Group.objects.filter(**{'is_default': True})
        if group:
            user.groups.add(*group)

    def _create_user(self, username, email, password, **extra_fields):
        """
        Creates and saves a User with the given username, email and password.
        """
        if not username:
            raise ValueError('The given username must be set')
        # email = self.normalize_email(email)
        with transaction.atomic():
            records = None
            try:
                records = extra_fields['records']
                del extra_fields['records']
            except:
                pass

            email = None
            user = self.model(username=username, email=email, **extra_fields)
            user.set_password(password)
            user.save(using=self._db)
            self.set_default_group(user)
            if records:
                user.records.add(*records)
            return user

    def create_user(self, username, email, password, **extra_fields):
        extra_fields.setdefault('is_staff', False)
        extra_fields.setdefault('is_admin', False)
        return self._create_user(username, email, password, **extra_fields)

    def create_superuser(self, username, email, password, **extra_fields):
        extra_fields.setdefault('is_staff', True)
        extra_fields.setdefault('is_admin', True)
        extra_fields.setdefault('is_superuser', True)
        if extra_fields.get('is_staff') is not True:
            raise ValueError('Superuser must have is_staff=True')
        print("创建超级用户")
        return self._create_user(username, email, password, **extra_fields)

    __login_type__ = -1

    def get_login_type(self):
        return self.__login_type__

    def get_by_natural_key(self, username):

        ret = None
        try:
            ret = self.get(Q(username=username) | Q(openId=username) | Q(phoneNumber=username))
        except:
            raise self.model.DoesNotExist

        if ret:
            if ret.username == username or ret.phoneNumber == username:
                self.__login_type__ = 0
            else:
                self.__login_type__ = 2

        return ret
